﻿from flask import Flask, g, render_template, request,flash,redirect,url_for,Blueprint
import pymysql,json,datetime,json
from .login.login import *
from .setting import *
from flask_cors import CORS
log_blue = Blueprint('log',__name__)


def json_encoder(obj):
    if isinstance(obj, datetime.datetime):
        return obj.strftime("%Y-%m-%d %X")
    elif isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d")
@log_blue.route('/sys/log/list')
# @login_required
def loglist():
	if request.args.get('username'):like = request.args.get('username')
	else:like=''
	if request.args.get('page'):page = request.args.get('page')
	else:page=1
	if request.args.get('limit'):limit = request.args.get('limit')
	else:limit=10
	# print(like,page,limit)
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_log WHERE  username LIKE '%"+like+"%'  LIMIT "+str(limit) +" OFFSET " +str((int(page)-1)*int(limit))
	sqlcount = "SELECT count(*) from sys_log  WHERE  username LIKE '%"+like+"%'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'id':dataList1[i][0],'username':dataList1[i][1],'operation':dataList1[i][2],'method':dataList1[i][3],'params':dataList1[i][4],'time':dataList1[i][5],'ip':dataList1[i][6],'createDate':dataList1[i][7]})
		cursor.execute(sqlcount)
		count = cursor.fetchall()[0][0]
	except Exception as e:
		return "Error: unable to fetch data from sys_log"+str(e)
	db.close()
	data={
			'msg': 'success',
			'code': 0,
			'page': {
				'totalCount': len(dataList),
				'pageSize': 10,
				'totalPage': 1,
				'currPage': 1,
				'list': dataList
				}
			}
	return json.dumps(data,default=json_encoder)
@log_blue.route('/sys/log/save',methods=['POST'])
# @login_required
def logsave():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'username' in d.keys():username = d['username']
		else:username=''
		if 'operation' in d.keys():operation = d['operation']
		else:operation=''
		if 'method' in d.keys():method = d['method']
		else:method=''
		if 'params' in d.keys():params = d['params']
		else:params=''
		if 'time' in d.keys():time = d['time']
		else:time=''
		if 'ip' in d.keys():ip = d['ip']
		else:ip=''
		if 'createDate' in d.keys():createDate = d['createDate']
		else:createDate=''
	elif request.form:
		username = request.form['username']
		operation = request.form['operation']
		method = request.form['method']
		params = request.form['params']
		time = request.form['time']
		ip = request.form['ip']
		createDate = request.form['createDate']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = 'insert into sys_log (username,operation,method,params,time,ip,create_date) values('+"'"+str(username)+"',"+"'"+str(operation)+"',"+"'"+str(method)+"',"+"'"+str(params)+"',"+"'"+str(time)+"',"+"'"+str(ip)+"',"+"'"+str(createDate)+"')"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to save data from sys_log"+str(e)
	db.close()
	
	data={
      'msg': 'success',
      'code': 0
    }
	return json.dumps(data,default=json_encoder)
@log_blue.route('/sys/log/update',methods=['POST'])
# @login_required
def logupdate():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'id' in d.keys():id = d['id']
		else:id=''
		if 'username' in d.keys():username = d['username']
		else:username=''
		if 'operation' in d.keys():operation = d['operation']
		else:operation=''
		if 'method' in d.keys():method = d['method']
		else:method=''
		if 'params' in d.keys():params = d['params']
		else:params=''
		if 'time' in d.keys():time = d['time']
		else:time=''
		if 'ip' in d.keys():ip = d['ip']
		else:ip=''
		if 'createDate' in d.keys():createDate = d['createDate']
		else:createDate=''
	elif request.form:
		id = request.form['id']
		username = request.form['username']
		operation = request.form['operation']
		method = request.form['method']
		params = request.form['params']
		time = request.form['time']
		ip = request.form['ip']
		createDate = request.form['createDate']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	cursor = db.cursor()
	sql ="UPDATE sys_log SET username='"+str(username)+"',operation='"+str(operation)+"',method='"+str(method)+"',params='"+str(params)+"',time='"+str(time)+"',ip='"+str(ip)+"',create_date='"+str(createDate)+"'"+ "WHERE id = '"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_log"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@log_blue.route('/sys/log/delete',methods=['POST'])
# @login_required
def logdelete():
	# print("content_type:", request.headers.get("content_type"))
	# print("data:", request.data)
	# print("data:", str(request.data, 'UTF-8'))
	# print("form:", request.form)
	# print("files:", request.files)
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'id' in d.keys():id = d['id']
		else:id=''
	elif request.form:
		id = request.form['id']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="DELETE FROM sys_log WHERE id='"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_log"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@log_blue.route('/sys/log/info')
@log_blue.route('/sys/log/info/<id>')#for update
# @login_required
def loginfo(id=None):
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="SELECT * from sys_log where  id='"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		log={'id':dataList1[0][0],'username':dataList1[0][1],'operation':dataList1[0][2],'method':dataList1[0][3],'params':dataList1[0][4],'time':dataList1[0][5],'ip':dataList1[0][6],'createDate':dataList1[0][7]}
		data={
				'msg': 'success',
				'code': 0,
				'log': log
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_log"+str(e)
	db.close()
@log_blue.route('/sys/log/select') #for other talbe's selector
# @login_required
def logselect():
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_log"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList1:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'id':dataList1[i][0],'username':dataList1[i][1],'operation':dataList1[i][2],'method':dataList1[i][3],'params':dataList1[i][4],'time':dataList1[i][5],'ip':dataList1[i][6],'createDate':dataList1[i][7]})
		# print(dataList)
		data={
				'msg': 'success',
				'code': 0,
				'list': dataList
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_role"+str(e)
	db.close()	
	
	
	


